import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_plugin/base/controller/base_controller.dart';
import 'package:get/get.dart';

import '../../../constant/sp_key.dart';
import '../../../ext/get_extension.dart';
import '../../../net/api_respository.dart';
import '../../../net/data/login_data.dart';
import '../../../net/http_url.dart';
import '../../../routes/router.dart';
import '../../../routes/router_util.dart';
import '../../../util/aes_utils.dart';
import '../../../util/log_util.dart';
import '../../../util/sputil.dart';
import 'login_sms_code_state.dart';

class LoginSmsCodeLogic extends BaseController<LoginSmsCodeLogic> {
  final LoginSmsCodeState state = LoginSmsCodeState();

  int count = 60;
  late Timer _timer;
  bool isSendLoginCode = false; //  防止多次点击

  @override
  void onInit() {
    super.onInit();
    state.phone = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
    countdown();
  }

  ///倒计时
  void countdown() {
    count = 60;
    state.buttonText.value = "$count秒";
    state.buttonCanClick.value = false;

    _timer = Timer.periodic(const Duration(milliseconds: 1000), (v) {
      if (count == 1) {
        print("========结束时操作 ");
        state.buttonText.value = "重新发送";
        state.buttonCanClick.value = true;
        _timer.cancel(); //取消定时器
      } else {
        count--;
        state.buttonText.value = "$count秒";
        state.buttonCanClick.value = false;
      }
    });
  }

  @override
  void loadNet() {
    // TODO: implement loadNet
  }

  void quickLogin(String code) {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    var queryParameters = <String, dynamic>{};
    queryParameters['phone'] = AesUtils.encryptAes(plainText: state.phone);
    queryParameters['validateCode'] = code;
    ApiRepository.instance.request<LoginData>(HttpUrl.quickLogin,
        params: queryParameters, withLoading: true, loadText: '登陆中…', success: (loginData) {
      SPUtil.instance.put(SPKey.phone_input, state.phone);
      SPUtil.instance.put(SPKey.TOKEN, loginData.token!);
      SPUtil.instance.put(SPKey.phone, loginData.user!.phone!);
      SPUtil.instance.put(SPKey.name, loginData.user!.name!);
      SPUtil.instance.put(SPKey.avatar, loginData.user!.avatar!);
      SPUtil.instance.put(SPKey.notSetPassword, loginData.notSetPassword!);
      SPUtil.instance.put(SPKey.isLogin, true);
      SPUtil.instance.put(SPKey.uid, loginData.user!.uid!);
      Get.offAllNamed(AppRoutes.home);
    }, error: (e) {
      showToast(e.message ?? "登录失败");
    });
  }

  void sendLoginCode(String phone) {
    if (isSendLoginCode) {
      return;
    }
    isSendLoginCode = true;
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    var queryParameters = <String, dynamic>{};
    queryParameters['phone'] = AesUtils.encryptAes(plainText: phone);
    ApiRepository.instance.request<String>(HttpUrl.sendLoginCode, params: queryParameters, success: (it) {
      LogD("sendLoginCode $it");
      isSendLoginCode = false;
      countdown();
    }, error: (e) {
      isSendLoginCode = false;
      LogD("sendLoginCode err ${e.code} ${e.message}");
      if (e.code == "204") {
        GetExtension.showCommonDialog(
          content: "您是“臻情守护关爱端”用户，请注销“关爱端”账户后再来注册",
          negaVisible: false,
          posiText: "确定",
          posiTap: () {},
        );
      } else if (e.code == "111") {
        showToast("验证码发送频繁，请稍后再试");
      } else {
        showToast(e.message ?? "获取验证码失败");
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 在页面回收或滑动复用回收的时候一定要把 timer 清除
    if (_timer != null) {
      if (_timer.isActive) {
        _timer.cancel();
      }
    }
  }
}
